<template>
	<view class="content">
		<cu-custom bgColor="bg-white" :isBack="true">
			<block slot="backText">{{$t('back')}}</block>
			<block slot="content"><text class="text-black text-bold">{{i18n.title}}</text></block>
		</cu-custom>
		<view class="padding">
			<text>{{i18n.tips}}</text>
		</view>
		<form id="formEmplotee" @submit="formSubmit">
			<view v-if="typelist.length>0" @click="showPicker=true" class="cu-form-group">
				<view class="title">{{i18n.type}}</view>
				<view class="picker">
					{{selectedIndex[0]>-1?typelist[selectedIndex[0]].vname:i18n.typeTips}}
				</view>
				<!-- <picker name="leavetype" @change="TypePickerChange" :value="typeindex" :range="typelist" range-key="vname">
					<view class="picker">
						{{typeindex>-1?typelist[typeindex].vname:i18n.typeTips}}
					</view>
				</picker> -->
			</view>
			<view style="height: 25upx;"></view>
			<view @click="ChoiceTime('start')" class="cu-form-group">
				<view class="title">{{i18n.startTime}}</view>
				<text style="padding-right: 25upx;">{{starttime.title}}</text>
			</view>
			<view @click="ChoiceTime('end')" class="cu-form-group">
				<view class="title">{{i18n.endTime}}</view>
				<text style="padding-right: 20upx;">{{endtime.title}}</text>
			</view>
			<view class="cu-form-group">
				<view class="title">{{i18n.timeCount}}({{timetype=='hour'?i18n.hour:i18n.day}})</view>
				<input style="text-align: right;" disabled v-model="leavecount" name="leavecount"></input>
			</view>
			<view style="height: 20upx;"></view>
			<view class="cu-form-group align-start">
				<view class="response">
					<view class="title">{{i18n.reason}}</view>
					<textarea name="leavereason" maxlength="-1" :placeholder="i18n.reasonHint"></textarea>
				</view>
			</view>
			<view class="cu-bar bg-white margin-top">
				<view class="action">
					{{i18n.image}}
				</view>
				<view class="action">
					{{imgList.length}}/4
				</view>
			</view>
			<view class="cu-form-group">
				<view class="grid col-4 grid-square flex-sub">
					<view class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="ViewImage" :data-url="imgList[index]">
						<image :src="imgList[index]" mode="aspectFill"></image>
						<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
							<text class='cuIcon-close'></text>
						</view>
					</view>
					<view class="solids" @tap="ChooseImage" v-if="imgList.length<4">
						<text class='cuIcon-cameraadd'></text>
					</view>
				</view>
			</view>
			<view class="cu-bar bg-white margin-top">
				<view class="action">
					{{i18n.approval}}
				</view>
				<view style="padding-right: 30upx;">
					<!-- <text class="cuIcon-settingsfill text-blue">流程设置</text> -->
				</view>
			</view>

			<approval :title="i18n.appPerson" :subtitle="appData.length>0?appData.length+i18n.perApproval:i18n.appPersonHint"
			 :options="appData" @addEvent="addEvent" @delete="delApproval"></approval>
			<!-- <view style="height: 180upx;"></view> -->
			<view class="bottom-float margin-top">
				<button class="response" :disabled="loadding" style="background-color: #5599FF;" :loading="loadding" type="primary"
				 form-type="submit">{{$t('submit')}}</button>
			</view>
		</form>
		<sPicker :cancelText="$t('cancel')" :confirmText="$t('sure')" @confirm="confirm" :visible.sync="showPicker" :list="[typelist]"
		 textKey="vname" v-model="selectedIndex"></sPicker>
		<select-date :name="choicename" @complete="TimeComplete" :timetype="timetype" :open="opendate" @change="SelectChange"></select-date>
	</view>
</template>

<script>
	import {
		pathToBase64,
		base64ToPath
	} from '@/components/image-tools/index.js'
	import selectDate from '@/components/selectdate/selectdate.vue'
	import Approval from '@/components/approval/approval.vue'
	import sPicker from '@/components/s-picker/index.vue';
	export default {
		components: {
			Approval,
			selectDate,
			sPicker
		},
		computed: {
			i18n() {
				return this.$t('leave')
			},
		},
		data() {
			return {
				//时间选择
				opendate: false,
				choicename: 'start',
				starttime: {
					title: this.$t('leave').selectTips,
					timestamp: 0,
					time: ''
				},
				endtime: {
					title: this.$t('leave').selectTips,
					timestamp: 0,
					time: ''
				},
				timetype: 'day',
				vminimum: 1,
				leavecount: 0,
				// end
				loadding: false,
				//请假类型
				typelist: [],
				typeindex: -1,
				//
				imgList: [],
				appData: [], //审批人
				showPicker: false,
				selectedIndex: [0],
			}
		},
		onLoad(options) {
			this.$constant.checkUserInfo()
			// this.InitTypeList()
			let types = options.types
			let index = parseInt(options.index)
			console.log(index)
			if(typeof(types)!='undefined'){
				// console.log('types = ',types)
				this.typelist = JSON.parse(types)
				this.typeindex = index
				this.selectedIndex[0] = index
				this.RestTimeType(this.typelist[index].vminimum)
			}	
		},
		methods: {
			//请假类型 start
			confirm(e) {
				// console.log(e[0])
				this.selectedIndex = e
				this.RestTimeType(this.typelist[this.selectedIndex[0]].vminimum)
			},
			InitTypeList() {
				try {
					let pages = getCurrentPages()
					let prePage = pages[pages.length - 2]
					var data = prePage.leaveTypeList
					var index = prePage.index
					this.typeindex = index
					this.selectedIndex[0] = index
					this.typelist = data
					this.RestTimeType(data[index].vminimum)
					console.log('typelist2', data)
				} catch (e) {
					console.log('leaveTypeList or index is undefined')
				}
			},
			TypePickerChange(e) {
				this.typeindex = e.detail.value
				this.RestTimeType(this.typelist[this.typeindex].vminimum)
				// console.log(e)
			},
			//请假类型 end
			//时间选择 start
			ChoiceTime(type) {
				this.opendate = true
				this.choicename = type
			},
			TimeComplete(e) {
				if (e.name == 'start') {
					this.starttime = e.date
					console.log(this.starttime.time)
					if (this.endtime.timestamp != 0) {
						if (new Date(this.starttime.time) > new Date(this.endtime.time)) {
							this.leavecount = 0
							this.endtime = {
								title: this.i18n.selectTips,
								timestamp: 0,
								time: ''
							}
						} else {
							this.CountDuration()
						}
					}
				} else {
					this.endtime = e.date
					console.log(this.starttime.time)
					if (this.starttime.timestamp != 0) {
						if (new Date(this.starttime.time) > new Date(this.endtime.time)) {
							this.leavecount = 0
							this.starttime = {
								title: this.i18n.selectTips,
								timestamp: 0,
								time: ''
							}
						} else {
							this.CountDuration()
						}
					}
				}
				// console.log(e)
			},
			SelectChange(e) {
				if (!e.show) {
					this.opendate = false
				}
			},
			RestTimeType(vminimum) {
				this.starttime = {
					title: this.i18n.selectTips,
					timestamp: 0,
					time: ''
				}
				this.endtime = {
					title: this.i18n.selectTips,
					timestamp: 0,
					time: ''
				}
				this.leavecount = 0
				this.vminimum = vminimum
				// console.log(vminimum)
				//重置时间选择类型
				switch (vminimum) {
					case '1': //表示按天请假
						this.timetype = 'day'
						break;
					case '2': //表示按半天请假
						this.timetype = 'noon'
						break;
					case '3': //表示按小时请假
						this.timetype = 'hour'
						break;
					default:
						break;
				}
				// console.log(this.timetype)
			},
			//计算请假时长
			CountDuration() {
				let requestData = {
					userid: getApp().globalData.userid,
					vminimum: this.vminimum,
					leavestime: this.starttime.time,
					leaveetime: this.endtime.time
				}
				if (this.vminimum == 2) {
					requestData.lstime = this.starttime.noon + 1
					requestData.letime = this.endtime.noon + 1
				}
				// console.log(requestData)
				uni.request({
					url: this.$constant.BASEURL + this.$constant.COUNT_LEAVE_TIME,
					method: "POST",
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					data: requestData,
					success: (res) => {
						// console.log(res.data)
						if (res.data.code == 0) {
							this.leavecount = res.data.data
						} else {
							this.leavecount = 0
							this.endtime = {
								title: this.i18n.selectTips,
								timestamp: 0,
								time: ''
							}
							uni.showModal({
								content: res.data.message,
								showCancel: false,
								cancelText: this.$t('sure'),
								confirmText: this.$t('cancel')
							})
						}
					}
				});
			},
			//时间选择 end
			ChooseImage() {
				let that = this
				uni.chooseImage({
					count: 4, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						// console.log(res.tempFilePaths)
						res.tempFilePaths.forEach(function(item) {
							pathToBase64(item)
								.then(base64 => {
									if (that.imgList.length < 4) {
										that.imgList.push(base64)
									}

								})
						})
						// console.log(that.imgList)
					}
				});
			},
			ViewImage(e) {
				uni.previewImage({
					urls: this.imgList,
					current: e.currentTarget.dataset.url
				});
			},
			DelImg(e) {
				uni.showModal({
					title: this.$t('notice'),
					content: this.i18n.deleteImgTips,
					cancelText: this.i18n.deleteActionSure,
					confirmText: this.i18n.deleteActionCancel,
					success: res => {
						if (res.confirm) {
							this.imgList.splice(e.currentTarget.dataset.index, 1)
						}
					}
				})
			},
			addEvent() {
				uni.navigateTo({
					url: '../contacts/contacts-2'
				})
			},
			delApproval(e) {
				this.appData.splice(e.index, 1)
			},
			formSubmit(e) {
				console.log(e)
				let value = e.detail.value

				if (this.selectedIndex[0] == -1) {
					uni.showToast({
						title: this.i18n.typeNoSelect,
						icon: 'none'
					})
					return
				}

				if (this.leavecount <= 0) {
					uni.showToast({
						title: this.i18n.typeCountError,
						icon: 'none'
					})
					return
				}

				if (value.leavereason == '') {
					uni.showToast({
						title: this.i18n.reasonHint,
						icon: 'none'
					})
					return
				}

				if (this.imgList.length > 4) {
					uni.showToast({
						title: this.i18n.moreImage,
						icon: 'none'
					})
					return
				}

				if (this.appData.length <= 0) {
					uni.showToast({
						title: this.i18n.appPersonHint,
						icon: 'none'
					})
					return
				}

				// console.log(value.leavetype)
				// let testimgs = ['image/png;base64,iVBORw0KGgoAAAANSUh++EU+gAA+\nBDgAAAeACAYAAAArYecKAAAgAElEQVR4XnS']
				let approval = ''
				for (let i = this.appData.length - 1; i >= 0; i--) {
					approval += this.appData[i].id + ','
				}

				// console.log("审批人", approval)
				let submitdata = {
					userid: getApp().globalData.userid,
					sysCompanyCode: getApp().globalData.unitno,
					vminimum: this.vminimum,
					leavestime: this.starttime.time,
					leaveetime: this.endtime.time,
					leavehour: value.leavecount,
					leavereason: value.leavereason,
					approval: approval,
					ltype: this.typelist[this.selectedIndex[0]].id,
					leaveimg: JSON.stringify(this.imgList)
				}
				if (this.vminimum == 2) {
					submitdata.lstime = this.starttime.noon + 1
					submitdata.letime = this.endtime.noon + 1
				}
				console.log(submitdata)
				this.loadding = true
				//开始提交
				uni.request({
					// url: 'http://huaan.lsyat.com/' + this.$constant.SUBMIT_LEAVE,
					url: this.$constant.BASEURL + this.$constant.SUBMIT_LEAVE,
					method: "POST",
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					data: submitdata,
					complete: (res) => {
						this.loadding = false
						console.log(res.data)
						if (res.data.code == 0 && res.data.data != '') {
							uni.redirectTo({
								url: `leavedetails?leaveid=${res.data.data}`
							})
						} else {
							uni.showToast({
								title: res.data.message,
								icon: 'none'
							})
						}
					}
				});

			}
		}
	}
</script>

<style>
	/* 	.img {
		background: url(../../../static/icon_increase_blue.png);
	} */

	.bottom-float {
		padding: 25upx;
		background-color: #FFFFFF;
		bottom: 0;
		width: 100%;
		/* position: fixed; */
		/* display: flex; */
		/* justify-content: center; */
	}

	.approval-group {
		direction: rtl;
		unicode-bidi: bidi-override;
		padding: 0 10upx 0 40upx;
		display: inline-block;
	}

	.approval-group .cu-avatar {
		/* margin-left: -30upx; */
		border: 4upx solid #f1f1f1;
		vertical-align: middle;
	}

	.approval-group .cu-avatar.sm {
		margin-left: -20upx;
		border: 1upx solid #f1f1f1;
	}
</style>
